/** @desc 事件节流 */
// @TODO: 补充示例文件路径
/** @example path */

import { genThrottle } from '@/utils/gen';
import { isElement, isFunction } from '@/utils/is';
import { NativeEventnames } from '../utils/type';

/** @typedef {import('../utils/type').Binding} Binding  */

const PREFIX = '__throttle_';

export default {
	/**
	 * 节点挂载完成后调用
	 * @param {HTMLElement} el
	 * @param {Binding} binding
	 */
	mounted(el, binding) {
		const { arg, value } = binding;
		if (
			arg &&
			value &&
			isFunction(value) &&
			isElement(el) &&
			NativeEventnames.includes(arg)
		) {
			el[PREFIX + arg] = genThrottle(value);
			el.addEventListener(arg, el[PREFIX + arg]);
		}
	},
	/**
	 * 节点卸载前调用
	 * @param {HTMLElement} el
	 * @param {Binding} binding
	 */
	beforeUnmount(el, binding) {
		const arg = binding.arg;
		if (
			arg &&
			NativeEventnames.includes(arg) &&
			isElement(el) &&
			el[PREFIX + arg]
		) {
			el.removeEventListener(arg, el[PREFIX + arg]);
			el[PREFIX + arg] = null;
			delete el[PREFIX + arg];
		}
	},
};
